package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.BcriptUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        if (!BcriptUtils.verifyPassword(password, employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /*
     * 添加员工
     *
     * */
    @Override
    public void save(EmployeeDTO employeeDTO) {

        System.out.println("拦截器：线程id," + Thread.currentThread().getId());

        Employee addEmp = new Employee();
        // spring框架，提供的工具方法：两个对象属性的拷贝
        BeanUtils.copyProperties(employeeDTO, addEmp);
       /* addEmp.setName(employeeDTO.getName());
        addEmp.setPhone(employeeDTO.getPhone());
        addEmp.setUsername(employeeDTO.getUsername());
        addEmp.setIdNumber(employeeDTO.getIdNumber());*/

        //1.补全基础属性
        addEmp.setUpdateUser(BaseContext.getCurrentId());
        addEmp.setCreateUser(BaseContext.getCurrentId());
        addEmp.setCreateTime(LocalDateTime.now());
        addEmp.setUpdateTime(LocalDateTime.now());

        //2.设置默认密码（加盐加密）
        addEmp.setPassword(BcriptUtils.hashPassword(PasswordConstant.DEFAULT_PASSWORD));

        //3.设置用户默认状态
        addEmp.setStatus(StatusConstant.ENABLE);

        //4.调用持久层，添加员工信息（Employee）
        employeeMapper.insert(addEmp);
    }

    /*
     * 条件加分页
     *
     * */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //1.使用PageHelepr实现分页查询，开启分页
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        //2.正常调用持久层mapper条件查询员工 (动态代理)
        Page page = (Page) employeeMapper.selectPageByCondition(employeePageQueryDTO.getName());

        //3.封装查询结果
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getResult());
        return pageResult;
    }

    /*
     *启用，禁用员工账号
     * */
    @Override
    public void startOrStop(Integer status, Long id) {
        //1.调用持久层，更新员工信息
        employeeMapper.update(Employee.builder()
                .status(status)
                .id(id)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build());
    }

    /*
     * 查询员工详情信息
     *
     * */
    @Override
    public Employee a(Long id) {
        Employee employee = employeeMapper.a(id);

        return employee;
    }

    /*
    * 更新员工信息
    * */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        // 构建实体类，将controllerr层传递的DTO转换成entity
        Employee emp = new Employee();

        BeanUtils.copyProperties(employeeDTO,emp);
        emp.setUpdateTime(LocalDateTime.now());
        emp.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.update(emp);
    }

}
